package com.chen;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfInt;
import org.opencv.face.LBPHFaceRecognizer;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

/**
 * 数据采集并生成数据集
 * @author scorpius
 */
public class DataAcquisition {
    
    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }
    
    
    public static void main(String[] args) throws FileNotFoundException, IOException {
        String path = "/home/scorpius/Pictures/orl_faces/images.txt";
        LBPHFaceRecognizer model = LBPHFaceRecognizer.create();
        
        List<Mat> images = new ArrayList<>();
        Mat labels = new Mat();
        Sequence sequence = new Sequence(images, labels);
        sequence.fill(path);
        //此模型相对另外的模型要更快捷,并且是以整数储存
        model.train(images, labels);
        //Mat img = images.get(images.size() - 1);
        //int predict_label = model.predict_label(img);
        //System.out.println("检出标记:" + predict_label);
        //model.save("/home/scorpius/Pictures/orl_faces/LBPH.json");//964113行
        model.save("/home/scorpius/Pictures/orl_faces/LBPH.xml");//598267行
    }
}

/**
 * 序列填充方法类
 * @author scorpius
 */
class Sequence {

    private final List<Mat> images;
    private final Mat labels;

    public Sequence(List<Mat> images, Mat labels) {
        this.images = images;
        this.labels = labels;
    }

    public void fill(String path) throws FileNotFoundException, IOException {
        File file = new File(path);
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null) {
            String[] split = line.split(" ");
            Mat imread = Imgcodecs.imread(split[0]);
            //既使你的图像是灰度也要进行这一步，否则可能报的错挺操蛋的
            Imgproc.cvtColor(imread, imread, Imgproc.COLOR_BGR2GRAY);
            images.add(imread);
            MatOfInt matOfInt = new MatOfInt(Integer.parseInt(split[split.length - 1]));
            labels.push_back(matOfInt);
        }
    }
}
